package pers.qianyu.module.system.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.qianyu.module.comment.dao.CommentDao;
import pers.qianyu.module.core.domain.logging.entity.RequestLogPO;
import pers.qianyu.module.core.domain.system.vo.ChartInfoVO;
import pers.qianyu.module.core.domain.system.vo.StatisticInfoVO;
import pers.qianyu.module.image.dao.ImageDao;
import pers.qianyu.module.image.dao.LabelDao;
import pers.qianyu.module.logging.dao.RequestLogDao;
import pers.qianyu.module.system.dao.SysUserDao;
import pers.qianyu.module.system.service.StatisticInfoService;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;

/**
 * @author mizzle rain
 * @date 2021-05-02 14:21
 */
@Service("statisticService")
public class StatisticInfoServiceImpl implements StatisticInfoService {
    @Autowired
    private ImageDao imageDao;
    @Autowired
    private LabelDao labelDao;
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private CommentDao commentDao;
    @Autowired
    private RequestLogDao requestLogDao;

    @Override
    public StatisticInfoVO getStatisticInfo() {
        Integer imageCount = imageDao.selectCount(null);
        Integer labelCount = labelDao.selectCount(null);
        Integer userCount = sysUserDao.selectCount(null);
        Integer commentCount = commentDao.selectCount(null);
        return StatisticInfoVO.Builder.aStatisticInfoVO()
                .commentCount(Long.valueOf(commentCount))
                .imageCount(Long.valueOf(imageCount))
                .labelCount(Long.valueOf(labelCount))
                .userCount(Long.valueOf(userCount))
                .build();
    }

    @Override
    public ChartInfoVO getChartInfo() {
        ArrayList<String> days = new ArrayList<>();
        ArrayList<Long> counts = new ArrayList<>();
        for (int i = 7; i > 0; i--) {
            String day = LocalDateTime.now().minusDays(i)
                    .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            days.add(day);
            QueryWrapper<RequestLogPO> queryWrapper = new QueryWrapper<>();
            long start = DateUtil.parse(day).toJdkDate().toInstant().toEpochMilli();
            long end = DateUtil.parse(LocalDateTime.now().minusDays(i - 1)
                    .format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
                    .toJdkDate().toInstant().toEpochMilli();
            queryWrapper.between("create_time", start, end);
            Integer count = requestLogDao.selectCount(queryWrapper);
            counts.add(Long.valueOf(count));
        }
        return new ChartInfoVO(days, counts);
    }
}
